import { App } from 'antd';
import { Key, useEffect, useState } from 'react';

import knowService from '@/api/services/knowService';
import { PaginationProps } from '@/common';
import { Input } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import NotData from '@/components/NotData';
import Tables from '@/components/tables/tables';
import useModal from '@/hooks/use-modal/useModal';
import { OptimizedistType } from '@/types/know/know';

import DocumentModals from './DocumentModals';
import datasetService from '@/api/services/datasetService';
import TipsModals from '@/components/modals/TipsModals';

interface DocumentOptimizationProps {
  visible: boolean;
  onClose: () => void;
  onOk: () => void;
}

const DocumentOptimization = ({ visible, onClose, onOk }: DocumentOptimizationProps) => {
  const modal = useModal(
    'wrongly',
    'optimization',
    'sensitive',
    'repetition',
    'document',
    'delete',
  );
  const [search, setSearch] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [total, setTotal] = useState(0);
  const [paginationProps, setPaginationProps] = useState({
    page: 1,
    pageSize: 10,
    offset: 0,
    searchText: '',
  });
  const [dataSource, setDataSource] = useState<OptimizedistType[]>([]);
  const [collectionItem, setCollectionItem] = useState<OptimizedistType>({} as OptimizedistType);
  const [type, setType] = useState<'wrongly' | 'optimization' | 'sensitive' | 'repetition'>(
    'wrongly',
  );
  const { message } = App.useApp();

  const statusStyleMap = {
    upload_publish: {
      text: '审批中',
      classNames: 'bg-functional-green text-primary',
    },
    upload_pass: {
      text: '已入库',
      classNames: 'bg-fill-2  text-text-5',
    },
    delete_pass: {
      text: '已入库',
      classNames: 'bg-fill-2  text-text-5',
    },
    upload_reject: {
      text: '上传驳回',
      classNames: 'bg-functional-red text-error',
    },
    delete_reject: {
      text: '删除驳回',
      classNames: 'bg-functional-red text-error',
    },
    delete_publish: {
      text: '删除、审批中',
      classNames: 'bg-functional-orange text-warning',
    },
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      render: (text: string) => (
        <div className="flex items-center ">
          <div>
            <SvgIcon color="#9e69fa" size={20} className="mr-1" icon="bxs--file" />
          </div>
          <span className="truncate">{text}</span>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'reviewStatus',
      key: 'reviewStatus',
      width: 150,
      render: (status: keyof typeof statusStyleMap) => {
        const style = statusStyleMap[status] || {};
        return (
          <div
            className={style.classNames}
            style={{
              padding: '2px 8px',
              borderRadius: 4,
              display: 'inline-flex',
              alignItems: 'center',
            }}
          >
            {style.text || status}
          </div>
        );
      },
    },
    {
      title: '知识库',
      dataIndex: 'datasetName',
      key: 'datasetName',
      width: 200,
      render: (text: string) => (
        <div className="flex items-center ">
          <span className="truncate">{text}</span>
        </div>
      ),
    },
    {
      title: '待优化内容',
      dataIndex: 'message',
      key: 'message',
      width: 200,
      render: (text: string) => <span className="text-@warning-color">{text}</span>,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: OptimizedistType, record: OptimizedistType) => (
        <div className="flex gap-2">
          <a
            className="flex cursor-pointer items-center text-@brand-color"
            onClick={() => {
              setCollectionItem(record);
              const typeArr = record?.optimize_text || [];
              if (Array.isArray(typeArr) && typeArr.length > 1) {
                setType('optimization');
              } else if (Array.isArray(typeArr) && typeArr.length === 1) {
                const t = typeArr[0] || '';
                if (t.includes('错别字')) setType('wrongly');
                else if (t.includes('敏感词')) setType('sensitive');
                else if (t.includes('重复')) setType('repetition');
                else setType('optimization');
              } else {
                setType('optimization');
              }
              modal.document.open();
            }}
          >
            <SvgIcon icon="edit" size="16" className="mr-1" />
            处理
          </a>
          <a
            className="flex cursor-pointer items-center "
            onClick={async () => {
              try {
                if (record.optimize_text.length === 1) {
                  if (record.optimize_text[0].includes('重复')) {
                    await knowService.similarityIngore({
                      datasetId: [record.datasetId],
                      collectionId: [record.collectionId],
                    });
                  } else {
                    await knowService.ignoreAutoCorrect({
                      collectionId: record.collectionId,
                      appId: record.appId,
                      type: record.optimize_text[0].includes('错别字') ? 'correct' : 'sensitive',
                      status: 0,
                    });
                  }
                } else {
                  const hasWrong = (record.optimize_text || []).some((t) => t.includes('错别字'));
                  const hasSensitive = (record.optimize_text || []).some((t) =>
                    t.includes('敏感词'),
                  );
                  const hasRepeat = (record.optimize_text || []).some((t) => t.includes('重复'));

                  const tasks: Promise<any>[] = [];
                  if (hasWrong) {
                    tasks.push(
                      knowService.ignoreAutoCorrect({
                        collectionId: record.collectionId,
                        appId: record.appId,
                        type: 'correct',
                        status: 0,
                      }),
                    );
                  }
                  if (hasSensitive) {
                    tasks.push(
                      knowService.ignoreAutoCorrect({
                        collectionId: record.collectionId,
                        appId: record.appId,
                        type: 'sensitive',
                        status: 0,
                      }),
                    );
                  }
                  if (hasRepeat) {
                    tasks.push(
                      knowService.similarityIngore({
                        datasetId: [record.datasetId],
                        collectionId: [record.collectionId],
                      }),
                    );
                  }
                  await Promise.all(tasks);
                }

                message.success('忽略成功');
                getOptimizedistList({
                  page: paginationProps.page,
                  pageSize: paginationProps.pageSize,
                  offset: paginationProps.offset,
                  searchText: '',
                });
              } catch (error) {
                message.error('忽略失败');
              }
            }}
          >
            <SvgIcon icon="message-ic21" size="16" className="mr-1" />
            忽略
          </a>
          <a
            className="flex cursor-pointer items-center !text-@error-color"
            onClick={() => {
              modal.delete.open();
              setCollectionItem(record);
            }}
          >
            <SvgIcon icon="message-ic3" size="16" className="mr-1" />
            删除
          </a>
        </div>
      ),
    },
  ];

  useEffect(() => {
    if (visible) {
      getOptimizedistList({
        page: paginationProps.page,
        pageSize: paginationProps.pageSize,
        offset: paginationProps.offset,
        searchText: search,
      });
    }
  }, [paginationProps, visible, search]);

  const getOptimizedistList = async (params: PaginationProps) => {
    try {
      const res = await knowService.getOptimizedist(params);
      setDataSource(res.data);
      setTotal(res.total);
    } catch (error) {
      message.error('获取文档优化列表失败');
    }
  };

  const handleClose = () => {
    setPaginationProps({
      page: 1,
      pageSize: 10,
      offset: 0,
      searchText: '',
    });
    setSearch('');
    setSelectedRowKeys([]);
    onClose();
  };

  const changeDelete = async (ids: string[], type: 'single' | 'multiple') => {
    try {
      if (type === 'single') {
        await datasetService.deleteDatasetFile({ ids });
      } else {
        const item = dataSource.filter((item) => ids.includes(item.collectionId));
        await datasetService.deleteDatasetFile({
          ids,
          batchList: item.map((item) => ({
            ids,
            appId: item.appId,
          })),
        });
      }
      getOptimizedistList({
        page: paginationProps.page,
        pageSize: paginationProps.pageSize,
        offset: paginationProps.offset,
        searchText: '',
      });
      setSearch('');
      setSelectedRowKeys([]);
      message.success('删除成功');
      modal.delete.close();
    } catch (error) {
      console.log(error);
    }
  };
  const changeIgnore = async () => {
    const item = dataSource.filter((item) => selectedRowKeys.includes(item.collectionId));
    if (!item.length) return;
    try {
      const tasks: Promise<any>[] = [];

      tasks.push(
        knowService.ignoreAutoCorrect({
          type: 'correct',
          status: 1,
          ignoreList: item.map((item) => ({
            collectionId: item.collectionId,
            appId: item.appId,
          })),
        }),
      );
      tasks.push(
        knowService.ignoreAutoCorrect({
          type: 'sensitive',
          status: 1,
          ignoreList: item.map((item) => ({
            collectionId: item.collectionId,
            appId: item.appId,
          })),
        }),
      );
      tasks.push(
        knowService.similarityIngore({
          datasetId: item.map((item) => item.datasetId),
          collectionId: item.map((item) => item.collectionId),
        }),
      );
      await Promise.all(tasks);

      message.success('忽略成功');
      getOptimizedistList({
        page: paginationProps.page,
        pageSize: paginationProps.pageSize,
        offset: paginationProps.offset,
        searchText: '',
      });
      setSelectedRowKeys([]);
    } catch (error) {
      message.error(error);
    }
  };

  return (
    <>
      <Modals
        open={visible}
        onCancel={handleClose}
        title="文档优化"
        width={1000}
        footer={null}
        maskClosable={false}
        onOk={onOk}
      >
        {/* 搜索栏 */}
        <div className="mb-4 flex items-center">
          <Input
            placeholder="搜索"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPaginationProps({
                page: 1,
                pageSize: 10,
                offset: 0,
                searchText: e.target.value,
              });
            }}
            prefix={<SvgIcon icon="search" size={16} />}
            className="h-[32px] !w-[240px] border-@brand-color"
          />
          {selectedRowKeys.length > 0 && (
            <div className="flex items-center gap-2">
              <span className="w-[80px] text-[#1D2129]">
                已选择 <span className="font-semibold">{selectedRowKeys.length}</span> 项
              </span>
              <div
                className="flex  h-8 w-[78px] cursor-pointer items-center justify-center rounded-md border  border-@brand-color-disabled bg-@brand-color-light px-2 text-@brand-color"
                onClick={changeIgnore}
              >
                <SvgIcon icon="message-ic21" size="16" className="mr-1" />忽 略
              </div>

              <div
                className={`ml-4 flex h-8 w-[78px] cursor-pointer items-center justify-center rounded-md border border-@error-color-disabled bg-@error-color-light px-2 text-@error-color-hover`}
                onClick={() => {
                  changeDelete(selectedRowKeys as string[], 'multiple');
                }}
              >
                <SvgIcon icon={'message-ic3'} className="mr-1" size={20} />
                删除
              </div>
            </div>
          )}
        </div>

        {total > 0 ? (
          <div className="flex  flex-1 flex-col ">
            <Tables
              columns={columns}
              dataSource={dataSource}
              pagination={false}
              locale={{ emptyText: <NotData fontText="暂无数据" /> }}
              rowSelection={{
                type: 'checkbox',
                selectedRowKeys,
                onChange: (selectedRowKeys) => {
                  setSelectedRowKeys(selectedRowKeys);
                },
              }}
              rowKey="collectionId"
              className="border border-gray-100"
              paginationProps={{
                total,
                current: paginationProps.page,
                pageSize: paginationProps.pageSize,
                onChange: (page: number, pageSize: number) => {
                  setPaginationProps({
                    page,
                    pageSize,
                    offset: (page - 1) * pageSize,
                    searchText: '',
                  });
                },
              }}
              scroll={{ y: 400 }}
            />
          </div>
        ) : (
          <div className="flex h-[400px] flex-1 flex-col items-center justify-center">
            <NotData fontText="暂无数据" />
          </div>
        )}
      </Modals>

      <DocumentModals
        type={type}
        collectionItem={collectionItem}
        visible={modal.document.isOpen}
        onCancel={() => {
          modal.document.close();
          getOptimizedistList({
            page: paginationProps.page,
            pageSize: paginationProps.pageSize,
            offset: paginationProps.offset,
            searchText: '',
          });
          setSearch('');
        }}
      />
      <TipsModals
        open={modal.delete.isOpen}
        onCancel={modal.delete.close}
        onOk={() => {
          changeDelete([collectionItem.collectionId], 'single');
        }}
      >
        删除文件后无法恢复，确认删除？
      </TipsModals>
    </>
  );
};

export default DocumentOptimization;
